﻿(function ($) {
    // formpanel
    function getPanelId(buttonId) {
        return buttonId.split("_")[0];
    }

    function getPanelInputWithXmlString(panelId, xmlTemplate) {
        var xml = $(utility.xml.convertXmlStringToDoc(xmlTemplate));
        var xml = utility.xml.fillXmlDocWithHtmlContainer(panelId, xml);
        return xml;
    }

    function setPanelInputWithXmlString(panelId, xmlTemplate) {
        var xml = $(utility.xml.convertXmlStringToDoc(xmlTemplate));
        //alert("fill data for " + panelId);
        utility.xml.fillHtmlContainerInputsWithXmlDoc(xml, panelId);
        //alert("complete fill data for " + panelId);
    }

    function setGuidInputValue(inputControl, newValue) {
        utility.control.setInputValue(inputControl, newValue);
    }

    function getDataXmlString(taskGuid, dataType, dataGuid) {
        var result = dataService.getData(taskGuid, dataGuid, dataType);
        return result;
    }

    function getDataXmlDom(taskGuid, dataType, dataGuid) {
        var xmlStr = getDataXmlString(taskGuid, dataType, dataGuid);
        return $(utility.xml.convertXmlStringToDoc(xmlStr));
    }

    function executeSubmit() {
        //alert("submit");
        var panelId = getPanelId(this.id);
        var inputValidated = true;
        var inputForm = $('#' + panelId).find("form");
        if (inputForm)
            inputValidated = inputForm.form('validate');
        if (inputValidated) {
            var opts = $('#' + panelId).data("formpanel");
            var template = opts["formTemplate"];
            //var guidInput = opts["dataGuidInput"];
            var guidNode = opts.guidNode;
            var dataType = opts["dataType"];
            //var dataGuid = $(guidInput).val();
            //var dataGuid = $(guidNode).text();
            var xmlPara = getPanelInputWithXmlString("#" + panelId, template);
            var dataGuid = xmlPara.find(guidNode).text();
            xmlPara.find("Document").attr("DataGuid", dataGuid);
            result = dataService.setData(opts.taskGuid, dataGuid, dataType, utility.xml.convertXmlDocToString(xmlPara));
            opts.onExecuteComplete(result);
        }
        return false;
    }

    function executeCancel() {
        var panelId = getPanelId(this.id);
        //alert("cancel " + panelId);
        var opts = $('#' + panelId).data("formpanel");
        switch (opts.formStyle) {
            case "window":
                utility.page.closeTab();
                break;
            case "dialog":
                utility.page.closeDialog();
                break;
        }
    }

    function executeQuery() {
        //alert("query");
        var panelId = getPanelId(this.id);
        var inputValidated = true;
        var inputForm = $('#' + panelId).find("form");
        if (inputForm)
            inputValidated = inputForm.form('validate');
        if (inputValidated) {
            var opts = $('#' + panelId).data("formpanel");
            var template = opts["formTemplate"];
            var xmlPara = getPanelInputWithXmlString("#" + panelId, template);
            result = dataService.transformData(opts.taskGuid, utility.xml.convertXmlDocToString(xmlPara));
            opts.onExecuteComplete(result);
            resizePanel("#" + panelId);
        }
        return false;
    }

    function executeReset() {
        var panelId = getPanelId(this.id);
        //alert(tableId);
        utility.control.resetInput("#" + panelId);
    }

    function resizePanel(target) {
        $(target).panel("panel").triggerHandler("_resize");
    }

    $.fn.formpanel = function (options, param) {
        if (typeof options == "string") {
            return $.fn.formpanel.methods[options](this, param);
        }

        options = options || {};
        return this.each(function () {
            var panelId = this.id;
            var state = $(this).data("formpanel");
            var buttonDivStyle = "";
            var opts;
            if (state) {
                opts = $.extend(state.options, options);
            } else {
                var customOptions = $.fn.formpanel.parseOptions(this);
                var formType = customOptions["formType"];
                if (formType == undefined) {
                    formType = options["formType"];
                    if (formType == undefined) {
                        return false;
                    }
                }
                var xmlDom;

                var actionCode = "";
                var dataGuid = "";
                //$(this).attr("title",opts.queryButtonText);
                switch (formType) {
                    case "query":
                        opts = $.extend({}, $.fn.formpanel.defaults, $.fn.formpanel.defaults.query, customOptions, options);
                        break;
                    case "edit":
                        //alert("edit " + dataGuid);
                        opts = $.extend({}, $.fn.formpanel.defaults, $.fn.formpanel.defaults.edit, customOptions, options);
                        if (opts.formStyle == "dialog") {
                            var editPara = $.fn.szjt_pageParameter("editParameter");
                            actionCode = editPara.actionCode;
                            dataGuid = editPara.selectedList;
                        } else {
                            actionCode = opts.actionCode;
                            dataGuid = opts.dataGuid;
                        }
                        //                        actionCode = utility.page.getQueryString("actionCode");
                        var guidNode = opts.guidNode;
                        xmlDom = getDataXmlDom(opts.taskGuid, opts.dataType, (dataGuid != "" && dataGuid != undefined ? dataGuid : "0"));
                        if (!dataGuid || dataGuid == "" || actionCode == "copy") {
                            var newGuid = dataService.getNewGuid();
                            setGuidInputValue(opts.guidInput, newGuid);
                            xmlDom.find(guidNode).text(newGuid);
                        }
                                                if (opts.formStyle == "dialog") {
                                                    $.parser.onComplete = function () { setPanelInputWithXmlString("#" + panelId, utility.xml.convertXmlDocToString(xmlDom)); };
                                                } else {
                                                    setPanelInputWithXmlString("#" + panelId, utility.xml.convertXmlDocToString(xmlDom));
                                                }
//                        setPanelInputWithXmlString("#" + panelId, utility.xml.convertXmlDocToString(xmlDom));
                        break;
                    case "display":
                        //alert("edit " + dataGuid);
                        opts = $.extend({}, $.fn.formpanel.defaults, $.fn.formpanel.defaults.display, customOptions, options);
                        var dataGuid = opts.dataGuid;
                        var guidNode = opts.guidNode;
                        if (dataGuid) {
                            xmlDom = getDataXmlDom(opts.taskGuid, opts.dataType, (dataGuid != "" ? dataGuid : "1"));
                            //$.parser.onComplete = function () { 
                            setPanelInputWithXmlString("#" + panelId, utility.xml.convertXmlDocToString(xmlDom));
                            // };
                        }
                        break;
                }
                buttonDivStyle = "width:100%;left:5%;text-align:center;";
//                switch (opts.formStyle) {
//                    case undefined, "window":
//                        buttonDivStyle = "width:90%;left:5%;text-align:center;";
//                        break;
//                    case "dialog":
//                        buttonDivStyle = "position:relative;width:90%;left:5%;bottom:10px;margin-left:0px;text-align:center;";
//                        break;
//                }
                $(this).data("formpanel", opts);
                if (buttonDivStyle.length > 0) {
                    $(this).prepend("<form id=\"form_" + panelId + "\" method=\"post\">");
                    $(this).append('<div id="' + panelId + '_formButtons" style=\"' + buttonDivStyle + '\">' +
                    '<a id="' + panelId + '_executeButton"></a>' +
                    '　　　　　　　　' +
                    '<a id="' + panelId + '_restoreButton"></a>' +
                    '</div>');
                    $(this).append("</form>");
                    $("#" + panelId + "_executeButton").linkbutton({ text: opts.executeButtonText, iconCls: opts.executeButtonIcon });
                    //var queryButton = $("#" + panelId + "_buttonQuery");
                    //queryButton.click = executeQuery(this.id);
                    $("#" + panelId + "_executeButton").bind("click", opts.onExecute);
                    $("#" + panelId + "_restoreButton").linkbutton({ text: opts.restoreButtonText, iconCls: opts.restoreButtonIcon });
                    $("#" + panelId + "_restoreButton").bind("click", opts.onRestore);
                    $(this).bind("_execute", opts.onExecute);
                    $(this).bind("_restore", opts.onRestore);
                }
            }
            $(this).panel(opts);
            //$(this).bind("_resize", function () { alert("my resize"); });
        });
    };

    $.fn.formpanel.defaults = {
        width: 'auto',
        height: 'auto',
        left: null,
        top: null,
        content: null,
        onCollapse: function () { resizePanel(this); },
        onExpand: function () { resizePanel(this); },

        // below are extended attribs or functions
        fitwidth: true,
        formTemplate: '',
        taskGuid: '',
        dataType: '',
        dataGuid: undefined,
        dataGuidInput: '',
        onExecuteComplete: function (executeResult) { }
    };

    $.fn.formpanel.defaults.display = {
        formStyle: '',
        title: '',
        iconCls: '',
        collapsible: false,
        collapsed: false
    };

    $.fn.formpanel.defaults.query = {
        formStyle: "window",
        title: '查询条件',
        iconCls: 'icon-search',
        collapsible: true,
        collapsed: false,
        executeButtonText: '查 询',
        restoreButtonText: '重 置',
        executeButtonIcon: 'icon-search',
        restoreButtonIcon: 'icon-reload',
        onExecute: executeQuery,
        onRestore: executeReset
    };

    $.fn.formpanel.defaults.edit = {
        formStyle: "dialog",
        title: '',
        iconCls: '',
        collapsible: false,
        collapsed: false,
        border: false,
        executeButtonText: '提 交',
        restoreButtonText: '取 消',
        executeButtonIcon: 'icon-ok',
        restoreButtonIcon: 'icon-cancel',
        closeAfterSubmit: true,
        onExecute: executeSubmit,
        onRestore: executeCancel
    };

    $.fn.formpanel.parseOptions = function (target) {
        var t = $(target);
        return $.extend({}, $.fn.datagrid.parseOptions(target), {
            formType: (t.attr("formType") || undefined),
            formStyle: (t.attr("formStyle") || undefined),
            formTemplate: (t.attr("formTemplate") || undefined),
            executeButtonText: (t.attr("executeButtonText") || undefined),
            restoreButtonText: (t.attr("restoreButtonText") || undefined),
            executeButtonIcon: (t.attr("executeButtonIcon") || undefined),
            restoreButtonIcon: (t.attr("restoreButtonIcon") || undefined),
            formTemplate: (t.attr("formTemplate") || undefined),
            dataGuidInput: (t.attr("dataGuidInput") || undefined),
            dataType: (t.attr("dataType") || undefined),
            dataGuid: (t.attr("dataGuid") || undefined)
        });
    };


    $.fn.formpanel.methods = {
        formTemplate: function () { return queryXmlTemplate; }
    };
})(jQuery);